﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace WPFTestDemo
{
    /// <summary>
    /// 单元格边框线条容器。
    /// </summary>
    public class TableCellBorderContainer : UIElement
    {
        /// <summary>
        /// 线条子元素集合。
        /// </summary>
        private List<BorderLine> _visualChildren = new List<BorderLine>();

        /// <inheritdoc/>
        protected override int VisualChildrenCount => _visualChildren.Count;

        /// <inheritdoc/>
        protected override Visual GetVisualChild(int index)
        {
            return _visualChildren[index];
        }

        /// <inheritdoc/>
        protected override void ArrangeCore(Rect finalRect)
        {
            for (int i = 0; i < VisualChildrenCount; i++)
            {
                _visualChildren[i].Arrange(finalRect);
            }

            base.ArrangeCore(finalRect);
        }

        /// <inheritdoc/>
        protected override Size MeasureCore(Size availableSize)
        {
            Rect desiredRect = new Rect(new Point(), new Size());

            for (int i = 0; i < VisualChildrenCount; i++)
            {
                desiredRect = Rect.Union(desiredRect, _visualChildren[i].Bounds);
            }

            return desiredRect.Size;
        }

        /// <summary>
        /// 清空所有线条。
        /// </summary>
        public void Clean()
        {
            // List的Count接口的实现不存在 Count < 0情况。
            // 源码链接：https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs
            if (VisualChildrenCount == 0)
            {
                return;
            }

            foreach (var child in _visualChildren)
            {
                RemoveVisualChild(child);
            }
            _visualChildren.Clear();
            
            InvalidateMeasure();
        }

        /// <summary>
        /// 添加新的线条。
        /// </summary>
        public void AddLine(BorderLine newLine)
        {
            if (!_visualChildren.Contains(newLine))
            {
                _visualChildren.Add(newLine);
                AddVisualChild(newLine);
                InvalidateMeasure();
            }
        }

        /// <summary>
        /// 移除线条。
        /// </summary>
        public void RemoveLine(BorderLine oldLine)
        {
            if (_visualChildren.Contains(oldLine))
            {
                _visualChildren.Remove(oldLine);
                RemoveVisualChild(oldLine);
                InvalidateMeasure();
            }
        }
    }
}
